package tomenttosa.prunuus.example.util;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarFileUtils {

	public static String getCodeSourcePath(Class<?> clazz) throws Exception {
		ProtectionDomain protectionDomain = clazz.getProtectionDomain();
		CodeSource codeSource = protectionDomain.getCodeSource();
		URI location = codeSource == null ? null : codeSource.getLocation().toURI();
		String path = location == null ? null : location.getRawSchemeSpecificPart();

		if (path == null) {
			throw new IllegalStateException("Unable to determine code source archive");
		}

		return path;
	}

	public static File getCodeSourceFile(Class<?> clazz) throws Exception {
		String path = getCodeSourcePath(clazz);
		File root = new File(path);
		if (!root.exists()) {
			throw new IllegalStateException("Unable to determine code source archive from " + root);
		}
		return new File(path);
	}

	public static List<JarEntry> getJarEntry(File jar, String path) throws Exception {
		JarFile jarFile = new JarFile(jar);
		List<JarEntry> jarEntries = new ArrayList<JarEntry>();
		try {
			for (Enumeration<JarEntry> jarenum = jarFile.entries(); jarenum.hasMoreElements();) {
				JarEntry jarEntry = jarenum.nextElement();
//				System.out.println("debug:" +jarEntry.getName());
				if (path != null && path.trim().length() > 0 && jarEntry.getName().startsWith(path)) {
					jarEntries.add(jarEntry);
				}
			}
		} finally {
			jarFile.close();
		}

		return jarEntries;
	}
	
	public static List<URL> getJarURL(File jar, String path) throws Exception {
		JarFile jarFile = new JarFile(jar);
		List<URL> urls = new ArrayList<URL>();
		try {
			for (Enumeration<JarEntry> jarenum = jarFile.entries(); jarenum.hasMoreElements();) {
				JarEntry jarEntry = jarenum.nextElement();
//				System.out.println("debug:" +jarEntry.getName());
				if (path != null && path.trim().length() > 0 && jarEntry.getName().startsWith(path)) {
					URL url = new URL("jar:" + jar.toURI().toURL() + "!/" + jarEntry.getName() +"!/");
//					System.out.println("debug:" +url.toString());
					urls.add(url);
				}
			}
		} finally {
			jarFile.close();
		}

		return urls;
	}
	
	public static void loadJar(URL[] urls, ClassLoader parent){
		URLClassLoader classloader = new URLClassLoader(urls, parent);
		Thread.currentThread().setContextClassLoader(classloader);
	}

}
